package com.nf.action;

import com.nf.entity.User;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.interceptor.SessionAware;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.util.Map;

public class UserAction extends ActionSupport implements ModelDriven<User>,SessionAware {
    //定义为null，不要管它怎么来
    private Map<String, Object> session = null;

    private User user = new User();
    /*
    public User getUser() {
        System.out.println("getUser被调用了");
        return user;
    }

    public void setUser(User user) {
        System.out.println("setUser被调用了");
        this.user = user;
    }*/

    //登录用的
    public String login(){
        System.out.println("用户名:"+user.getUserName());
        if ("admin".equals(user.getUserName())&&"123456".equals(user.getUserPassword())){
            //登陆成功后,干什么？

            //ActionContext context = ActionContext.getContext();
            //第一种方法：通过context获得Map对象
            //主动获得实例
            //Map<String, Object> session = context.getSession();
            //注意，此处的session跟
            // HttpSession session = request.getSession();
            //不是同一个对象，但是使用起来是一样的
            //session.put("user",user);

            //第2种方法
            //对javaweb 产生强耦合
            //HttpServletRequest request = (HttpServletRequest)context.get(org.apache.struts2.StrutsStatics.HTTP_REQUEST);
            //HttpSession session = request.getSession();
            //session.setAttribute("user",user);

            //第3种方法，实现SessionAware直接注入实例
            System.out.println("session:"+session);
            session.put("user",user);

            return this.SUCCESS;
        }else {
            return this.ERROR;
        }
    }
    //跳转到登陆页面的方法
    public String loginView(){

        return "loginViewSuccess";
    }

    //不需要手动调用
    public User getModel() {
        //告诉struts，你帮我对user进行赋值
        System.out.println("struts 调用我们的getModel，获得user的实例");
        return this.user;
    }

    //用于被框架注入实例用的,不需要手动调用
    public void setSession(Map<String, Object> map) {
        session = map;
    }
}
